<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      .box1 {
        width: 200px;
        height: 200px;
        background-color: red;
      }

      .box2 {
        width: 100px;
        height: 100px;
        background-color: #2c3a47;
        position: absolute;
      }

      .outline {
        position: absolute;
        border: 2px solid black;
        pointer-events: none;
      }
    </style>
  </head>

  <body>
    <div class="box1">
      <div id="box2" class="box2"></div>
    </div>
    <script>
      // 获取子容器和轮廓元素
      var box2 = document.getElementById("box2");
      var outline = document.createElement("div");
      outline.classList.add("outline");

      // 存储子容器的初始位置和大小
      var initialX = box2.offsetLeft;
      var initialY = box2.offsetTop;
      var initialWidth = box2.offsetWidth;
      var initialHeight = box2.offsetHeight;

      // 鼠标按下事件处理函数
      box2.addEventListener("mousedown", function (e) {
        // 添加轮廓元素
        document.body.appendChild(outline);

        initialX = box2.offsetLeft;
        initialY = box2.offsetTop;
        initialWidth = box2.offsetWidth;
        initialHeight = box2.offsetHeight;

        // 设置轮廓元素的位置和大小
        outline.style.left = initialX + "px";
        outline.style.top = initialY + "px";
        outline.style.width = initialWidth + "px";
        outline.style.height = initialHeight + "px";
      });

      // 鼠标移动事件处理函数
      document.addEventListener("mousemove", function (e) {
        if (outline) {
          // 更新轮廓元素的位置
          outline.style.left = e.pageX - initialWidth / 2 + "px";
          outline.style.top = e.pageY - initialHeight / 2 + "px";
        }
      });

      // 鼠标松开事件处理函数
      document.addEventListener("mouseup", function (e) {
        if (outline) {
          // 删除轮廓元素
          document.body.removeChild(outline);

          // 更新子容器的位置和大小
          box2.style.left = e.pageX - initialWidth / 2 + "px";
          box2.style.top = e.pageY - initialHeight / 2 + "px";
          box2.style.width = initialWidth + "px";
          box2.style.height = initialHeight + "px";
        }
      });
    </script>
  </body>
</html>
